package se.rende.cardcatcher;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.RawContacts;
import android.widget.TextView;

/**
 * Handles vCard attachments or browser resources. Opens Contacts with option to add as new contact or to existing contact.
 *
 * @author Dag Rende
 */
public class CardCatcher extends Activity {
    private static final String[] phoneTagTable = {ContactsContract.Intents.Insert.PHONE, ContactsContract.Intents.Insert.SECONDARY_PHONE, ContactsContract.Intents.Insert.TERTIARY_PHONE};
    private static final String[] emailTagTable = {ContactsContract.Intents.Insert.EMAIL, ContactsContract.Intents.Insert.SECONDARY_EMAIL, ContactsContract.Intents.Insert.TERTIARY_EMAIL};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        try {
			if (getIntent().getScheme().equals("content")) {
				InputStream is = getContentResolver().openInputStream(getIntent().getData());
				BufferedReader reader = new BufferedReader(new InputStreamReader(is));
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				PrintWriter pw = new PrintWriter(baos);
				
				Intent i = new Intent(Intent.ACTION_INSERT_OR_EDIT);
				i.setType(RawContacts.CONTENT_ITEM_TYPE);

				Pattern fnPattern = Pattern.compile("FN:(.+)$");
				int phoneIndex = 0;
				Pattern phonePattern = Pattern.compile("TEL;CELL:(.+)$");
				int emailIndex = 0;
				Pattern emailPattern = Pattern.compile("EMAIL;INTERNET:(.+)$");

				while (true) {
					String line = reader.readLine();
					if (line == null) {
						break;
					}
					pw.println(line);
					
					Matcher matcher = fnPattern.matcher(line);
					if (matcher.matches()) {
						String name = matcher.group(1);
						pw.println("name=" + name);
						i.putExtra(ContactsContract.Intents.Insert.NAME, name);				
					}
					
					matcher = phonePattern.matcher(line);
					if (matcher.matches() && phoneIndex < phoneTagTable.length) {
						String match = matcher.group(1);
						pw.println("phone=" + match);
						i.putExtra(phoneTagTable[phoneIndex++], match);				
					}

					matcher = emailPattern.matcher(line);
					if (matcher.matches() && emailIndex < emailTagTable.length) {
						String match = matcher.group(1);
						pw.println("mail=" + match);
						i.putExtra(emailTagTable[emailIndex++], match);			
					}
				}
				reader.close();
				pw.close();
				
				TextView tv = (TextView) findViewById(R.id.tv);
				tv.setText(baos.toString());
				
				startActivity(i);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    @Override
    protected void onResume() {
    	super.onResume();
    	// don't show this view when back from contacts app
    	finish();
    }
}